import React, { createContext, useContext, useState, useEffect } from 'react';

// 创建主题上下文
const ThemeContext = createContext();

// 主题提供者组件
export const ThemeProvider = ({ children }) => {
  // 从本地存储获取主题设置
  const [isDarkMode, setIsDarkMode] = useState(() => {
    const savedSettings = localStorage.getItem('userSettings');
    if (savedSettings) {
      const { darkMode } = JSON.parse(savedSettings);
      return darkMode || false;
    }
    return false;
  });

  // 切换主题模式
  const toggleDarkMode = () => {
    setIsDarkMode(prevMode => {
      const newMode = !prevMode;
      
      // 更新本地存储中的设置
      const savedSettings = localStorage.getItem('userSettings');
      const settings = savedSettings ? JSON.parse(savedSettings) : {};
      settings.darkMode = newMode;
      localStorage.setItem('userSettings', JSON.stringify(settings));
      
      return newMode;
    });
  };

  // 监听主题变化，更新HTML属性
  useEffect(() => {
    if (isDarkMode) {
      document.documentElement.setAttribute('data-theme', 'dark');
    } else {
      document.documentElement.removeAttribute('data-theme');
    }
  }, [isDarkMode]);

  // 提供主题上下文值
  const themeContextValue = {
    isDarkMode,
    toggleDarkMode
  };

  return (
    <ThemeContext.Provider value={themeContextValue}>
      {children}
    </ThemeContext.Provider>
  );
};

// 自定义钩子，用于访问主题上下文
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme必须在ThemeProvider内部使用');
  }
  return context;
}; 